package com.emapp.lccode.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.viewModelScope
import com.amap.api.location.AMapLocationClient
import com.emapp.lccode.R
import com.emapp.lccode.adapter.GridImageAdapter
import com.emapp.lccode.adapter.MaterialSelectAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.BaseConfig.selectMaxImage
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.databinding.ActivityFeedbackBinding
import com.emapp.lccode.mode.OrderKtViewModel
import com.emapp.lccode.utils.DividerOrientation
import com.emapp.lccode.utils.GlideEngine
import com.emapp.lccode.utils.ImageFileCompressEngine
import com.emapp.lccode.utils.MeSandboxFileEngine
import com.emapp.lccode.utils.MyExternalPreviewEventListener
import com.emapp.lccode.utils.divider
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.grid
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.toStartActivity
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.utils.MediaUtils
import com.umeng.commonsdk.stateless.UMSLEnvelopeBuild.mContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 */
class FeedBackActivity : BaseActivity1<OrderKtViewModel, ActivityFeedbackBinding>(),
    MaterialSelectAdapter.OnButtonClickListener {
    var mData: ArrayList<LocalMedia> = arrayListOf()
    private val imageAdapter: GridImageAdapter by lazy { GridImageAdapter(this, mData) }
    lateinit var launcherResult: ActivityResultLauncher<Intent>
    var imageIds = ""
    var content = ""
    override fun initView(savedInstanceState: Bundle?) {
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        launcherResult = createActivityResultLauncher()
        mViewBind.lvTitle.tvTitle.text = "意见反馈"
        mViewBind.lvTitle.tvRight.visibility = View.GONE
        EventBus.getDefault().register(this)
        mViewBind.rvList.run {
            grid(4)
            adapter = imageAdapter
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter.run {
            selectMax = selectMaxImage
            setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
                override fun onItemClick(v: View?, position: Int) {
                    PictureSelector.create(this@FeedBackActivity)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .isPreviewFullScreenMode(true)
                        .setExternalPreviewEventListener(MyExternalPreviewEventListener(this@run))
                        .startActivityPreview(position, true, data)
                }

                override fun openPicture() {
                    // 进入相册
                    val selectionModel: PictureSelectionModel =
                        PictureSelector.create(this@FeedBackActivity)
                            .openGallery(SelectMimeType.ofImage())
                            .setSelectorUIStyle(PictureSelectorStyle())
                            .setImageEngine(GlideEngine.createGlideEngine()) //.setCropEngine(getCropFileEngine())
                            .setCompressEngine(ImageFileCompressEngine())
                            .setSandboxFileEngine(MeSandboxFileEngine())
                            .setSelectionMode(SelectModeConfig.MULTIPLE)
                            .isDisplayCamera(true)
                            .setMaxSelectNum(BaseConfig.selectMaxImage)
                            .setSelectedData(data)
                    selectionModel.forResult(launcherResult)
                }

            })
        }
    }

    override fun createObserver() {
        mViewModel.run {
            file.observe(this@FeedBackActivity) { resultState ->
                parseState(resultState, {
                    imageIds = if (imageIds.isEmpty()) {
                        it.id
                    } else {
                        imageIds + "," + it.id
                    }
                    if (mData.isNotEmpty()) upFile()
                    else {
                        dismissLoading()
                        replyAdd()
                        //Toaster.show("上传成功")
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            reply.observe(this@FeedBackActivity) { resultState ->
                parseState(resultState, {
                    Toaster.show("提交成功")
                    // EventBus.getDefault().post(EventBusModel(EventBusConfig.REFRESH_ORDER))
                    viewModelScope.launch {
                        delay(500)
                        finish()
                    }
                }, {
                    if (it.errorMsg.contains("file_ids")) {
                        Toaster.show("请上传图片")
                    } else {
                        Toaster.show(it.errorMsg)
                    }
                })
            }
        }

    }

    private fun createActivityResultLauncher(): ActivityResultLauncher<Intent> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList)
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: java.util.ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(mContext, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(mContext, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
        }
        val isMaxSize = result.size == imageAdapter.selectMax
        val oldSize: Int = imageAdapter.data.size
        imageAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
        imageAdapter.data.clear()
        imageAdapter.data.addAll(result)
        imageAdapter.notifyItemRangeInserted(0, result.size)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight,
            mViewBind.btOk
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.tv_add -> {
                    toStartActivity(WuLiaoActivity::class.java)
                }

                R.id.bt_ok -> {
                    content = mViewBind.tvContent.text.toString()
                    if (content.isEmpty()) {
                        Toaster.show("请输入内容")
                        return@setOnclickNoRepeat
                    }
                    mData.clear()
                    mData.addAll(imageAdapter.data)
                    imageIds = ""
                    if (mData.isNotEmpty()) {
                        showLoading("正在上传图片")
                        upFile()
                    } else {
                        replyAdd()
                    }
                }
            }
        }
    }

    private fun upFile() {
        if (!mData[0].availablePath.isNullOrBlank()) {
            val file = File(mData[0].availablePath)
            mViewModel.upFileFeedBack(file)
            mData.removeAt(0)
        } else {
            mData.removeAt(0)
            if (mData.isNotEmpty()) upFile()
            else {
                dismissLoading()
                replyAdd()
            }
        }
    }

    private fun replyAdd() {
        mViewModel.feedBack(content, imageIds)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.SELECT_MATERIAL -> {
            }

            else -> {}
        }
    }

    override fun onDelete(position: Int) {
    }

    @SuppressLint("CheckResult", "NotifyDataSetChanged")
    override fun onCount(position: Int) {

    }

}
